package fr.bda.cloud.util;

import java.io.File;
import java.io.OutputStream;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import fr.bda.cloud.data.DataDescriptor;
import fr.bda.cloud.data.StorageMode;
import fr.bda.cloud.storage.LocalStorageUnitConfiguration;
import fr.bda.cloud.storage.StorageUnitConfiguration;
import fr.bda.cloud.storage.StorageUnitType;

public class CloudJaxbFactory {

	public static JAXBContext getJaxbContext() {

		try {
			return JAXBContext.newInstance(DataDescriptor.class, StorageMode.class, StorageUnitType.class, Date.class, StorageUnitConfiguration.class, LocalStorageUnitConfiguration.class);
		} catch (JAXBException e1) {
			e1.printStackTrace();
		}

		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T> T unmarshal(File f, Class<T> clazz) {
		try {
			return (T) getJaxbContext().createUnmarshaller().unmarshal(f);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <T> void marshal(T obj, File f) {
		try {
			Marshaller marshaller = getJaxbContext().createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			marshaller.marshal(obj, f);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
	
	
	public static <T> void marshal(T obj, OutputStream os) {
		try {
			Marshaller marshaller = getJaxbContext().createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			marshaller.marshal(obj, os);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}
